package com.glsc.ngateway.platform.service.cmdb;

import com.glsc.ngateway.common.base.domain.mysql.cmdb.CmdbTableSequence;
import com.glsc.ngateway.common.base.repo.mysql.cmdb.CmdbTableSequenceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class SequenceProductService {

    @Autowired
    private CmdbTableSequenceRepository cmdbTableSequenceRepository;

    public synchronized String buildSequence(String fromTable) {
        //查询是否存在编号，存在则增加
        LocalDateTime d = LocalDateTime.now();
        CmdbTableSequence sequence = cmdbTableSequenceRepository.findOneByFromTableAndYear(fromTable,d.getYear());
        if (sequence == null){
            CmdbTableSequence sequenceNew =  new CmdbTableSequence();
            sequenceNew.setYear(d.getYear());
            sequenceNew.setFromTable(fromTable);
            sequenceNew.setSeq(1);
            cmdbTableSequenceRepository.save(sequenceNew);
            return d.getYear()+"_"+fromTable.toUpperCase()+"_"+String.format("%05d", 1);
        } else {
            sequence.setSeq(sequence.getSeq()+1);
            cmdbTableSequenceRepository.save(sequence);
            return d.getYear()+"_"+fromTable.toUpperCase()+"_"+String.format("%05d", sequence.getSeq());
        }
    }
}
